/*
 * DesktopApplication1View.java
 */
package org.simplexquery;

import nu.xom.ValidityException;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Nodes;
import nu.xom.ParsingException;
import nux.xom.xquery.XQueryUtil;
import org.xml.sax.XMLReader;

/**
 * The application's main frame.
 */
public class AppView extends FrameView {

    public AppView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = App.getApplication().getMainFrame();
            aboutBox = new AppAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        App.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        mainPanel = new javax.swing.JPanel();
        jScrollPaneXQuery = new javax.swing.JScrollPane();
        jTextAreaXQuery = new javax.swing.JTextArea();
        jButtonExecute = new javax.swing.JButton();
        jScrollPaneResult = new javax.swing.JScrollPane();
        jTextAreaResult = new javax.swing.JTextArea();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        openMenuItem = new javax.swing.JMenuItem();
        openUrlMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        Run = new javax.swing.JMenu();
        executeMenuItem = new javax.swing.JMenuItem();
        viewXmlMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.setLayout(new java.awt.GridBagLayout());

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(org.simplexquery.App.class).getContext().getResourceMap(AppView.class);
        jScrollPaneXQuery.setViewportBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jScrollPaneXQuery.viewportBorder.title"))); // NOI18N
        jScrollPaneXQuery.setName("jScrollPaneXQuery"); // NOI18N
        jScrollPaneXQuery.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jScrollPaneXQueryKeyPressed(evt);
            }
        });

        jTextAreaXQuery.setColumns(20);
        jTextAreaXQuery.setRows(5);
        jTextAreaXQuery.setName("jTextAreaXQuery"); // NOI18N
        jTextAreaXQuery.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextAreaXQueryKeyPressed(evt);
            }
        });
        jScrollPaneXQuery.setViewportView(jTextAreaXQuery);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 279;
        gridBagConstraints.ipady = 56;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        mainPanel.add(jScrollPaneXQuery, gridBagConstraints);

        jButtonExecute.setText(resourceMap.getString("jButtonExecute.text")); // NOI18N
        jButtonExecute.setName("jButtonExecute"); // NOI18N
        jButtonExecute.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExecuteActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 7;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(12, 6, 0, 0);
        mainPanel.add(jButtonExecute, gridBagConstraints);

        jScrollPaneResult.setViewportBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jScrollPaneResult.viewportBorder.title"))); // NOI18N
        jScrollPaneResult.setName("jScrollPaneResult"); // NOI18N

        jTextAreaResult.setColumns(20);
        jTextAreaResult.setRows(5);
        jTextAreaResult.setName("jTextAreaResult"); // NOI18N
        jScrollPaneResult.setViewportView(jTextAreaResult);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 385;
        gridBagConstraints.ipady = 130;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(6, 0, 0, 0);
        mainPanel.add(jScrollPaneResult, gridBagConstraints);

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        openMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        openMenuItem.setText(resourceMap.getString("openMenuItem.text")); // NOI18N
        openMenuItem.setName("openMenuItem"); // NOI18N
        openMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(openMenuItem);

        openUrlMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_U, java.awt.event.InputEvent.CTRL_MASK));
        openUrlMenuItem.setText(resourceMap.getString("openUrlMenuItem.text")); // NOI18N
        openUrlMenuItem.setName("openUrlMenuItem"); // NOI18N
        openUrlMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openUrlMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(openUrlMenuItem);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(org.simplexquery.App.class).getContext().getActionMap(AppView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        Run.setText(resourceMap.getString("Run.text")); // NOI18N
        Run.setName("Run"); // NOI18N

        executeMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0));
        executeMenuItem.setText(resourceMap.getString("executeMenuItem.text")); // NOI18N
        executeMenuItem.setName("executeMenuItem"); // NOI18N
        executeMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                executeMenuItemActionPerformed(evt);
            }
        });
        Run.add(executeMenuItem);

        viewXmlMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F6, 0));
        viewXmlMenuItem.setText(resourceMap.getString("viewXmlMenuItem.text")); // NOI18N
        viewXmlMenuItem.setName("viewXmlMenuItem"); // NOI18N
        viewXmlMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewXmlMenuItemActionPerformed(evt);
            }
        });
        Run.add(viewXmlMenuItem);

        menuBar.add(Run);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        org.jdesktop.layout.GroupLayout statusPanelLayout = new org.jdesktop.layout.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 419, Short.MAX_VALUE)
            .add(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(statusMessageLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 235, Short.MAX_VALUE)
                .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelLayout.createSequentialGroup()
                .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(statusMessageLabel)
                    .add(statusAnimationLabel)
                    .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openMenuItemActionPerformed
        // TODO add your handling code here:
        System.out.println("open File");
        JFileChooser fc = new JFileChooser();

        int returnVal = fc.showOpenDialog(mainPanel);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            xmlFile = fc.getSelectedFile();
            jTextAreaResult.setText("Load file " + xmlFile.getAbsolutePath() + " ... ");
            try {
                //XMLReader parser = new org.ccil.cowan.tagsoup.Parser(); // tagsoup parser
                //Document doc = new Builder(parser).build(url);
                doc = new Builder().build(xmlFile);
                this.docChanged();
                System.out.println(doc.toXML());
                jTextAreaResult.append("done.");
            } catch (ParsingException ex) {
                Logger.getLogger(AppView.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(AppView.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }//GEN-LAST:event_openMenuItemActionPerformed

    private void docChanged() {
        if (null == doc) {
            return;
        }
        if (null == viewXml) {
            viewXml = new ViewXML();
        }
        viewXml.setParent(this);
        viewXml.setXML(doc.toXML());
    }

    private void viewXML() {
        if (null == doc) {
            return;
        }
        if (null == viewXml) {
            viewXml = new ViewXML();
        }


        viewXml.setParent(this);
        viewXml.setVisible(true);
        viewXml.setXML(doc.toXML());

    }

    private void executeXQuery() {
        if (null == doc) {
            return;
        }
        jTextAreaResult.setText("");
        System.out.println(jTextAreaXQuery.getText());
        Nodes results = XQueryUtil.xquery(doc, jTextAreaXQuery.getText());
        for (int i = 0; i < results.size() && i < 100; i++) {
            System.out.println("node " + i + ": " + results.get(i).toXML());
            jTextAreaResult.append(results.get(i).toXML() + "\n");
            //System.out.println("node " + i + ": " + XOMUtil.toPrettyXML(results.get(i)));
        }
    }
    private void jButtonExecuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExecuteActionPerformed
        this.executeXQuery();
    }//GEN-LAST:event_jButtonExecuteActionPerformed

    private void jScrollPaneXQueryKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jScrollPaneXQueryKeyPressed
        // TODO add your handling code here:
        //System.out.println("Key " + evt.getKeyChar() + " pressed!");
        if (evt.getKeyChar() == java.awt.event.KeyEvent.VK_F5) {
            this.executeXQuery();
        }
    }//GEN-LAST:event_jScrollPaneXQueryKeyPressed

    private void jTextAreaXQueryKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextAreaXQueryKeyPressed
        // TODO add your handling code here:
        //System.out.println("Key " + evt.getKeyChar() + " pressed!");
        if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_F5) {
            this.executeXQuery();
        }
        if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_F6) {
            this.viewXML();
        }
    }//GEN-LAST:event_jTextAreaXQueryKeyPressed

    private void executeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_executeMenuItemActionPerformed
        // TODO add your handling code here:
        this.executeXQuery();
    }//GEN-LAST:event_executeMenuItemActionPerformed

    private void openUrlMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openUrlMenuItemActionPerformed
        // TODO add your handling code here:
        url = new InsertUrl();
        url.setParent(this);
        url.setVisible(true);

    }//GEN-LAST:event_openUrlMenuItemActionPerformed

    private void viewXmlMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewXmlMenuItemActionPerformed
        // TODO add your handling code here:
        this.viewXML();
    }//GEN-LAST:event_viewXmlMenuItemActionPerformed

    public void callBackFunction(String url) {
        try {
            System.out.println("CallBack: " + url);
            jTextAreaResult.setText("Load file from " + url + " ... ");
            XMLReader parser = new org.ccil.cowan.tagsoup.Parser(); // tagsoup parser
            doc = new Builder(parser).build(url);
            this.docChanged();
            jTextAreaResult.append("done.");
            System.out.println(doc.toXML());
        } catch (ParsingException ex) {
            Logger.getLogger(AppView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(AppView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu Run;
    private javax.swing.JMenuItem executeMenuItem;
    private javax.swing.JButton jButtonExecute;
    private javax.swing.JScrollPane jScrollPaneResult;
    private javax.swing.JScrollPane jScrollPaneXQuery;
    private javax.swing.JTextArea jTextAreaResult;
    private javax.swing.JTextArea jTextAreaXQuery;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem openMenuItem;
    private javax.swing.JMenuItem openUrlMenuItem;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JMenuItem viewXmlMenuItem;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private File xmlFile = null;
    private JDialog aboutBox;
    public Document doc = null;
    private InsertUrl url = null;
    private ViewXML viewXml = null;
}
